package sketch.specs;

import java.util.LinkedList;
import java.util.List;

import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Statement;
import org.eclipse.jdt.internal.core.dom.NaiveASTFlattener;

import sketch.ast.ASTUtils;
import sketch.util.Checker;

public class RedundantParenthesesRemover<T extends ASTNode> {
	
	public final T node;
	
	public RedundantParenthesesRemover(T node) {
		Checker.checkNull(node, "The given ASTNode could not be null!");
		this.node = node;
	}
	
	public T getResult() {
		ParenthesesRemovingVisitor visitor = new ParenthesesRemovingVisitor();
		T copy = ASTUtils.deepClone(node);
		copy.accept(visitor);
		return copy;
	}
	
	public MethodDeclaration removeRedundantParentheses(MethodDeclaration method) {
		return null;//return removeParenthesisInBlock(method.getBody());
	}
	
	public String removeParenthesisInBlock(Block block) {
		StringBuilder sb = new StringBuilder();
		
		List<Statement> blockStatements = block.statements();
		for(Statement statement : blockStatements) {
			if(statement instanceof Block) {
				sb.append(this.removeParenthesisInBlock((Block)statement));
			}
			else {
			    sb.append(statement.toString());
			}
		}
		
		return sb.toString();
	}
	
	
	public static class ParenthesesRemovingVisitor extends NaiveASTFlattener {
		//XXX did in a brute-force way
		@Override
		public boolean visit(Block block) {
			
			List<Statement> blockStatements = block.statements();
			if(blockStatements.size() == 0) {
				//only parenthesis
				return false;
			}
			
			List<Statement> replacing = new LinkedList<Statement>();
			int index = 0;
			for(Statement statement : blockStatements) {
				if(statement instanceof Block) {
					Block subBlock = (Block)statement;
					List<Statement> subStatements = subBlock.statements();
					for(Statement subStatement : subStatements) {
						subStatement.delete();
						replacing.add(subStatement);
					}
				} else {
					replacing.add(statement);
				}
				index++;
			}
			block.statements().clear();
			block.statements().addAll(replacing);
			
			
			
			return false;
		}
		
	}
}